package com.test.resumeanalysis.common

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.addCallback
import androidx.annotation.IdRes
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.viewbinding.ViewBinding
import com.test.resumeanalysis.viewModel.PublicViewModel

abstract class BaseVBFragment <VB : ViewBinding>(private val inflate: (LayoutInflater, ViewGroup?, Boolean) -> VB) : Fragment() {

    private var _binding: VB? = null
    val binding: VB get() = _binding!!

    open fun initView() = Unit
    open fun initEvent() = Unit

    open fun getNavigateId(): Int = 0
    protected open val enabledBack = false


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        _binding = inflate(inflater, container, false)
        return binding.root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initEvent()
    }

    open fun navigate(@IdRes resId: Int, args: Bundle? = null) {
        val navController = findNavController()
        val currentDestination = navController.currentDestination
        if (getNavigateId() == 0 || currentDestination?.id == getNavigateId()) {
            navController.navigate(resId, args)
        }
    }

    protected fun setupToolbar(toolbar: Toolbar, showBack: Boolean = false) {
        (activity as AppCompatActivity).also {
            it.setSupportActionBar(toolbar)
            it.supportActionBar?.apply {
                setDisplayShowTitleEnabled(false)
                setDisplayHomeAsUpEnabled(showBack)
            }
        }
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        requireActivity().onBackPressedDispatcher.addCallback(this, enabledBack) {
            onBackPressed()
        }
    }

    protected open fun onBackPressed() {
        val r = findNavController().popBackStack()
        if (!r) {
            requireActivity().finish()
        }
    }
}

